package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.AnnouncementApi;
import com.tanhua.dubbo.api.CommentApi;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.mongo.FriendApi;
import com.tanhua.model.domain.Announcement;
import com.tanhua.model.domain.User;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.vo.CommentVo;
import com.tanhua.model.vo.ContactVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.UserInfoVo;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.exception.ErrorResult;
import com.tanhua.server.interceptor.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Slf4j
@Service
public class MessagesService {
    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @DubboReference
    private UserApi userApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private CommentApi commentApi;
    @DubboReference
    private FriendApi friendApi;

    @DubboReference
    private AnnouncementApi announcementApi;

    /**
     * 根据环信id查询用户详情
     *
     * @param hxId
     * @return
     */
    public UserInfoVo findUserInfoByHuanxin(String hxId) {
        log.info("用户传输的环信id{}",hxId);
        //获取用户信息
        User user = userApi.getByHxID(hxId);
        //获取用户详细信息
        UserInfo userInfo = userInfoApi.findById(user.getId());
        //封装vo返回信息
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo, userInfoVo);
        if (userInfo.getAge() != null) {
            userInfoVo.setAge(String.valueOf(userInfo.getAge()));
        }
        return userInfoVo;
    }

    /**
     * 添加好友
     *
     * @param userId 好友id
     */
    public void contacts(Long userId) {
        //将好友关系注册到环信
        Boolean aBoolean = huanXinTemplate.addContact(Constants.HX_USER_PREFIX + UserHolder.getUserId()
                , Constants.HX_USER_PREFIX + userId);
        if (!aBoolean) {
            throw new BusinessException(ErrorResult.error());
        }
        //注册成功，将好友关系保存到mongo
        friendApi.save(UserHolder.getUserId(), userId);
    }

    /**
     * 分页查询联系人信息
     *
     * @param page     页码
     * @param pagesize 当页查询条数
     * @param keyword  条件
     * @return 联系人信息
     */
    public PageResult findFriends(Integer page, Integer pagesize, String keyword) {
        //1、调用API查询当前用户的好友数据 -- List<Friend>
        List<Friend> list = friendApi.findByUserId(UserHolder.getUserId(), page, pagesize);
        if (CollUtil.isEmpty(list)) {
            return new PageResult();
        }
        //2、提取数据列表中的好友id
        List<Long> friendIds = list.stream().map(item -> item.getFriendId()).collect(Collectors.toList());
        //3、调用UserInfoAPI查询好友的用户详情
        UserInfo userInfo = new UserInfo();
        userInfo.setNickname(keyword);
        Map<Long, UserInfo> map = userInfoApi.findByIds(friendIds, userInfo);
        //4、构造VO对象
        List<ContactVo> vos = new ArrayList<>();
        for (Friend friend : list) {
            UserInfo userInfo1 = map.get(friend.getFriendId());
            if (userInfo != null) {
                ContactVo vo = ContactVo.init(userInfo1);
                vos.add(vo);
            }
        }
        return new PageResult(page, pagesize, 0, vos);
    }

    /**
     * 查询公告列表
     *
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult announcements(Integer page, Integer pagesize) {
      List<Announcement>announcements= announcementApi.announcements(page,pagesize);
//        List<Map<String, Object>> collect = announcements.stream().map((item) -> {
//            Map<String, Object> map = new HashMap<>();
//            map.put("id", item.getId());
//            map.put("title", item.getTitle());
//            map.put("description", item.getDescription());
//            map.put("createDate", item.getCreated());
//            return map;
//        }).collect(Collectors.toList());
//        log.info(collect.toString());
        log.info(announcements.toString());
        return new PageResult(page,pagesize,announcements.size(),announcements);
    }

    /**
     * 查询喜欢列表
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult loves(Integer page, Integer pagesize) {
        List<Comment>comments= commentApi.loves(UserHolder.getUserId(),page,pagesize,3);
        log.info(comments.toString());
        //根据被评论人查询被评论人详细信息获取头像
        List<CommentVo> list = getCommentVos(comments);
        log.info("喜欢列表{}",list.toString());
        return new PageResult(page,pagesize,0,list);
    }

    /**
     * 查询点赞列表
     *
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult likes(Integer page, Integer pagesize) {
        List<Comment>comments= commentApi.comments(UserHolder.getUserId(),page,pagesize,1);
        log.info(comments.toString());
        //根据被评论人查询被评论人详细信息获取头像
        List<CommentVo> list = getCommentVos(comments);
        log.info("查询点赞列表{}",list.toString());
        return new PageResult(page,pagesize,0,list);
    }
    /**
     * 查询评论列表
     *
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult comments(Integer page, Integer pagesize) {
        List<Comment>comments= commentApi.comments(UserHolder.getUserId(),page,pagesize,2);
        log.info(comments.toString());
        List<CommentVo> list = getCommentVos(comments);
        log.info("查询点赞列表{}",list.toString());
        return new PageResult(page,pagesize,0,list);
    }
    //根据被评论人查询被评论人详细信息
    private List<CommentVo> getCommentVos(List<Comment> comments) {
        List<Long> collect = comments.stream().map(item -> item.getPublishUserId()).collect(Collectors.toList());
        log.info("被评论用户id：{}",collect.toString());
        List<UserInfo> userInfos = collect.stream().map(item -> userInfoApi.findById(item)).collect(Collectors.toList());
        log.info("用户详细信息：{}",userInfos.toString());
        List<CommentVo> list = new ArrayList<>();
        for (UserInfo userInfo : userInfos) {
            for (Comment comment : comments) {
                if (userInfo.getId() == comment.getPublishUserId()) {
                    CommentVo init = CommentVo.init(userInfo, comment);
                    log.info("返回信息：{}",init.toString());
                    list.add(init);
                }
            }
        }
        return list;
    }
}
